package com.centaline.androidsalesblog.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.api.RongTokenApi;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.RongTokenEvent;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.RongTokenRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 融云聊天登录Service
 */
public class RongLoginService extends Service {

    private CompositeSubscription compositeSubscription = new CompositeSubscription();

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d("onStartCommand");
        startLogin();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Logger.d("RongLoginService onDestroy");
        compositeSubscription.unsubscribe();
        super.onDestroy();
    }

    /**
     * 开始登录
     */
    private void startLogin() {
        SprfUtil.setString(this, SprfConstant.RONG_TOKEN, "");//清空上次的token
        compositeSubscription.add(RxDataBase
                .getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (userDo == null) {
                            tokenResult(2);
                        } else {
                            request(userDo);
                        }
                    }
                }));
    }

    /**
     * 请求
     */
    private void request(UserDo userDo) {
        RongTokenApi rongTokenApi = new RongTokenApi(RongLoginService.class, RongTokenRo.class, new IResponseListener<RongTokenRo>() {
            @Override
            public void onResponse(RongTokenRo rongTokenRo) {
                if (200 == rongTokenRo.getCode()) {
                    SprfUtil.setString(RongLoginService.this, SprfConstant.RONG_TOKEN, rongTokenRo.getToken());
                    tokenResult(0);
                } else {
                    tokenResult(2);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                tokenResult(1);
            }
        });
        rongTokenApi.setUserId(RongUserIdUtil.getCustomerId(userDo.getUserId()));
        rongTokenApi.setName(userDo.getNickName());
        rongTokenApi.setPortraitUri(userDo.getUserPhotoUrl());
        rongTokenApi.startRequest();
    }

    /**
     * token获取结果
     */
    private void tokenResult(int status) {
        EventBus.getDefault().post(new RongTokenEvent(status));
        stopSelf();
    }
}
